import { reqCartList, reqDeleteCartList, reqUpdateIsChecked } from "@/api";

const state = {
    shopCartInfo: [],
};

const mutations = {
    GetShopCart(state, shopCartInfo){
        state.shopCartInfo = shopCartInfo;
    }
};

const actions = {
    // 购物车列表
    async getShopCart({ commit }){
        let result = await reqCartList();
        console.log("cartList", result);
        if(result.code == 200 ){
            commit("GetShopCart", result.data)
        }
    },
    // 根据skuId删除购物车某一列表
    async deleteCartList({ commit }, skuId){
        let result = await reqDeleteCartList(skuId);
        console.log("deleteCartList" ,result)
        if(result.code == 200){
            return "ok";
        }else{
            return Promise.reject(new Error('faile'));
        }
    },
    // 根据skuId购物车更新勾选框状态
    async updateIsChecked({commit}, {skuId, isChecked}){
        let result = await reqUpdateIsChecked(skuId, isChecked)
        if(result.code == 200){
            return "ok";
        }else{
            return Promise.reject(new Error('faile'))
        }
    },
    // 删除已勾选商品
    deleteAllIsCheckedCart({getters, dispatch}){
        // console.log(context)    // {commit, dispatch, getters, state}    state和getters都能捞数据
        let PromiseAll = [];
        getters.cartInfo.cartInfoList.forEach(cartList => {
            let promise = cartList.isChecked == 1 ? dispatch("deleteCartList", cartList.skuId) : '';
            // console.log("deleteAllIsCheckedCart", promise);
            PromiseAll.push(promise);
        });
        return Promise.all(PromiseAll);
    },
    // 点击全部勾选
    updateAllIsChecked({state, dispatch}, isChecked){
        let PromiseAll = [];
        state.shopCartInfo[0].cartInfoList.forEach(cartList => {
            let promise = dispatch("updateIsChecked", {skuId: cartList.skuId, isChecked});
            PromiseAll.push(promise);
        })
        return Promise.all(PromiseAll);
    },
};

const getters = {
    cartInfo(){
        return state.shopCartInfo[0] || {};
    }
};

export default ({
    state,
    mutations,
    actions,
    getters
})